package com.next.cxy.film.controller.auth.controller;

import com.next.cxy.film.controller.auth.controller.vo.AuthRequestVO;
import com.next.cxy.film.controller.auth.controller.vo.AuthResponseVO;
import com.next.cxy.film.controller.auth.util.JwtTokenUtil;
import com.next.cxy.film.controller.common.BaseResponseVO;
import com.next.cxy.film.controller.exception.ParamErrorExcetion;
import com.next.cxy.film.service.common.exception.CommonServiceExcetion;
import com.next.cxy.film.service.user.INextUserTService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;/**/

@RestController
public class AuthController {
    @Autowired
    private INextUserTService nextUserTService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @RequestMapping(value = "auth", method = RequestMethod.POST)
    public BaseResponseVO auth(@RequestBody AuthRequestVO authRequestVO) throws ParamErrorExcetion, CommonServiceExcetion {
        authRequestVO.checkParam();
        boolean isValid = nextUserTService.userAuth(authRequestVO.getUsername(), authRequestVO.getPassword());
        if (isValid) {
            String randomKey = jwtTokenUtil.getRandomKey();
            String token = jwtTokenUtil.generateToken(authRequestVO.getUsername(), randomKey);
            AuthResponseVO build = AuthResponseVO.builder().randomKey(randomKey).token(token).build();
            return BaseResponseVO.success(build);
        } else {
            return BaseResponseVO.serviceFailed(1, "用户名或密码不正确");
        }
    }
}
